package com.jml.netty1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class Client {

	public static void main(String[] args) throws Exception {
		
		EventLoopGroup workgroup = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(workgroup)
				//客户端使用的channel
		.channel(NioSocketChannel.class)
		.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				sc.pipeline().addLast(new FixedLengthFrameDecoder(5));
				sc.pipeline().addLast(new StringDecoder());
				sc.pipeline().addLast(new ClientHandler());
			}
		});
		//future表示异步的获取通道
		ChannelFuture cf1 = bootstrap.connect("127.0.0.1", 8765).sync();
		//Unpooled.copiedBuffer("777".getBytes());  返回的是缓冲字节
		//buf
		Channel channel = cf1.channel();

		channel.writeAndFlush(Unpooled.copiedBuffer("12345aa717$_".getBytes()));
		channel.writeAndFlush(Unpooled.copiedBuffer("aaaaaaa727$_".getBytes()));
		channel.writeAndFlush(Unpooled.copiedBuffer("bbbbbbb737$_".getBytes()));
		channel.writeAndFlush(Unpooled.copiedBuffer("cccccc747$_".getBytes()));

		//sync表示异步，异步释放连接
		channel.closeFuture().sync();
		workgroup.shutdownGracefully();
		
	}
}
